package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

/**
 * HttpServletRequest 对象 相关的方法
 */
@WebServlet("/httpServletRequestDemo")
public class HttpServletRequestDemo extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 行相关 GET/POST
        req.getMethod(); // 获取请求方式
        req.getScheme(); // 获取请求方式
        req.getProtocol(); // 获取请求协议版本
        req.getRemoteUser(); // 获取请求的 url
        req.getLocalPort(); // 本应用容器的端口号
        req.getServerPort(); // 客户端发送请求时使用的端口号

        // 头相关
        req.getHeader("Accept"); // 获取单个请求头信息
        // 获取所有的头信息
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + ": " + req.getHeader(headerName));
        }

        // 参数相关 --- 新开一个 html 页面测试
        String userName = req.getParameter("userName");

        // 跟据参数名获取多个参数值
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbies));

        // 获取所有参数名
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String[] values = req.getParameterValues(parameterName);
            if (values.length > 1) {
                System.out.println(parameterName + ": " + Arrays.toString(values));
            }else {
                System.out.println(parameterName+ ": " + values[0]);
            }
        }

        // 返回所有参数的 Map 集合
        Map<String,String[]> parameterMap = req.getParameterMap();
    }

}
